package com.zhiwang.planet.ui

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.os.Process
import android.provider.Settings
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import androidx.appcompat.app.AlertDialog
import android.view.WindowManager
import com.afollestad.materialdialogs.MaterialDialog
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.mvp.v.ApkUpdateView
import com.zhiwang.planet.mvvm.model.entity.main.UpdateCheck
import com.zhiwang.planet.service.DownLoadService
import com.zhiwang.planet.ui.interf.UiProgress
import com.zhiwang.planet.util.execUpdateLogic
import com.zhiwang.planet.util.suicideAfterTransition
import kotlinx.android.synthetic.main.upgrade_dialog_layout.*
import kotlinx.android.synthetic.main.upgrade_dialog_layout.view.*

/**
 * 将更新页面用一个独立的Activity来做，而不是某些页面需要弹出更新窗口的时候
 * 都弹一个dialog，免去重复代码
 */
class UpdateActivity : BaseActivity(), ApkUpdateView, UiProgress {

    companion object {
        fun start(context: Context, updateCheck: UpdateCheck) {
            val intent = Intent(context, UpdateActivity::class.java)
            intent.putParcelableArrayListExtra("UpdateCheck", arrayListOf(updateCheck))
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        updateCheck = intent.getParcelableArrayListExtra<UpdateCheck>("UpdateCheck")[0]
    }


    override fun onResume() {
        super.onResume()
        if (permitted.not())
            onUpdate(updateCheck)
    }

    var alertDialog: AlertDialog? = null

    private lateinit var upgradeDialog: AlertDialog

    override fun onUpdate(updateCheck: UpdateCheck) {

        val currentCode = BuildConfig.VERSION_CODE
        if (currentCode < updateCheck.version) {

            if (execUpdateLogic(updateCheck, true).not()) {
                val rootView = layoutInflater.inflate(R.layout.upgrade_dialog_layout, null)

                rootView.upgrade_log.text = updateCheck.updateLog

                updateCheck.versionName?.apply {
                    rootView.upgrade_version.text = "版本$this"
                }

                upgradeDialog = AlertDialog.Builder(this)
                        .setView(rootView)
                        .setCancelable(false)
                        .create()
                rootView.upgrade_later.setOnClickListener {
                    upgradeDialog.dismiss()
                    suicideAfterTransition()
                }

                rootView.upgrade_now.setOnClickListener {
                    startUpdate(updateCheck)
//                    upgradeDialog.dismiss()
                }

                //transparent
                upgradeDialog.window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
                upgradeDialog.show()

            }
        } else {
            suicideAfterTransition()
        }

    }

    private lateinit var updateCheck: UpdateCheck

    private fun startUpdate(updateCheck: UpdateCheck) {
        this.updateCheck = updateCheck
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this@UpdateActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                val alertDialog = AlertDialog.Builder(this@UpdateActivity)
                        .setTitle("申请权限")
                        .setMessage("请求SD卡读写权限，下载最新安装包")
                        .setNegativeButton("允许") { dialog, which ->
                            ActivityCompat.requestPermissions(
                                    this@UpdateActivity,
                                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                                    110)
                            dialog.dismiss()
                        }
                        .setCancelable(false)
                        .create()
                alertDialog.show()

            } else {

                AlertDialog.Builder(this@UpdateActivity)
                        .setTitle("权限不足")
                        .setMessage("没有SD卡读写权限，无法下载最新安装包，请到应用管理页面授予权限")
                        .setNegativeButton("取消") { dialog, which ->
                            ActivityCompat.requestPermissions(
                                    this@UpdateActivity,
                                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                                    110)
                            dialog.dismiss()
                        }
                        .setPositiveButton("去设置") { dialog, which ->
                            val intent = Intent()
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                            intent.data = Uri.parse("package:$packageName")
                            startActivity(intent)
                            dialog.dismiss()
                        }
                        .create()
                        .show()
            }

        } else {
            //有权限
            permitted = true
            downLoadApk(updateCheck)
        }

    }

    private fun downLoadApk(updateCheck: UpdateCheck) {
     /*   val materialDialog = MaterialDialog.Builder(this)
                .title("版本升级")
                .content("正在下载安装包，请稍候")
                .progress(false, 100, false)
                .cancelable(false)
                .negativeText("取消")
                .dismissListener {
                    suicideAfterTransition()
                }
                .onNegative { dialog, _ ->
                    DownLoadService.stopDownload()
                    if (updateCheck.forceUpdate == 1) {
                        Process.killProcess(Process.myPid())
                    }
                    dialog.dismiss()
                }
                .show()*/
        DownLoadService.materialDialog = this
        DownLoadService.start(applicationContext, updateCheck.url, updateCheck.md5)
    }

    var permitted = false
    val TAG = "UpdateActivity"
    override fun onRequestPermissionsResult(requestCode: Int, @NonNull permissions: Array<String>, @NonNull grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 110) {
            for (gr in grantResults) {
                if (gr != PackageManager.PERMISSION_GRANTED)
                    return
            }
            permitted = true
            startUpdate(updateCheck)
        }
    }

    override fun onUiComplete() {
        upgradeDialog.dismiss()
    }

    override fun setUiProgress(progress: Int) {

        upgradeDialog?.download_progress?.isIndeterminate = false
        upgradeDialog?.download_progress?.progress = progress
    }

}
